

import java.io.*;

import java.security.*;

import javax.crypto.*;

import java.math.*;

import sun.misc.*;

//From Java Cryptography, By Jonathan Knudesn

public class SecretWriting2 {

	static class DummyDES implements Key

	{

		private byte[] b;

		public DummyDES(byte[] b) {this.b = b;}

		public String getAlgorithm() {return "DES";}

		public String getFormat() {return "RAW";}

		public byte[] getEncoded() {return b;}

	}

	static byte[] x = new BigInteger("43013e628f460468", 16).toByteArray();



	private static final String[] defaultArgs = {"-e", "this", "is", "a", "test"};

	public static void main(String[] args) throws Exception {

		if (args.length < 1) {

			args = defaultArgs;

		}



	//get a key



	Key key;

	try {

		ObjectInputStream in = new ObjectInputStream(

			new FileInputStream("SecretKey.ser"));

		key = (Key)in.readObject();

		in.close();

	}



	//Hopefully we have a key generated by a Java method. It is

	//stored in the file SecretKey.ser



	catch (FileNotFoundException fnfe) {

	  KeyGenerator generator = KeyGenerator.getInstance("DES");

	  generator.init(new SecureRandom());

	  key = generator.generateKey();

	  ObjectOutputStream out = new ObjectOutputStream(

		  new FileOutputStream("SecretKey.ser"));

	  out.writeObject(key);

	  out.close();

    }



//    key = new DummyDES(x);

    System.out.println("key.getAlgorithm() = " + key.getAlgorithm());

    System.out.println("key.getFormat() = " + key.getFormat());

    BigInteger encoded = new BigInteger(key.getEncoded());

    System.out.println("key.getEncoded() = " + encoded.toString(16));



    //Get a cipher object



    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");



    if (args[0].indexOf("e") != -1) { //Encypt the input string

		cipher.init(Cipher.ENCRYPT_MODE, key);

		String amalgam = args[1];

		for (int i = 2; i < args.length; i++)

		  amalgam += " " + args[i];

		System.out.println("You entered: " + amalgam);

		byte[] stringBytes = amalgam.getBytes("UTF8");

		byte[] raw = cipher.doFinal(stringBytes);

		BASE64Encoder encoder = new BASE64Encoder();

		String base64 = encoder.encode(raw);

		System.out.println("\n"+base64);

	    }

	 else if (args[0].indexOf("d") != -1) { //Decrypting the input string

		 System.out.println("\nDecrypting:\t" + args[1]);

		 cipher.init(Cipher.DECRYPT_MODE, key);

		 BASE64Decoder decoder = new BASE64Decoder();

		 byte[] raw = decoder.decodeBuffer(args[1]);

		 byte[] stringBytes = cipher.doFinal(raw);

		 String result = new String(stringBytes, "UTF8");

		 System.out.println("\n"+result);



	    }

	}

}